﻿using BasicInformation.ApiRead.Application.Command.Device;
using BasicInformation.Domain;
using BasicInformation.Dtos;
using BasicInformation.ErrorCode;
using BasicInformation.Infrastructure.Implement;
using Dapper;
using MediatR;
using MySqlX.XDevAPI.Common;
using System.Text;

namespace BasicInformation.ApiRead.Application.Handler.Device
{
    public class GetDeviceHandler : IRequestHandler<GetDeviceCommand, ApiPaging<DeviceModel>>
    {
        private readonly DatabaseContext db;
        private readonly ILogger<GetDeviceHandler> logger;

        public GetDeviceHandler(DatabaseContext db,ILogger<GetDeviceHandler> logger)
        {
            this.db = db;
            this.logger = logger;
        }
        public async Task<ApiPaging<DeviceModel>> Handle(GetDeviceCommand request, CancellationToken cancellationToken)
        {
            var paging = new ApiPaging<DeviceModel>();

            // 参数验证
            if (request.index <= 0) request.index = 1;
            if (request.size <= 0) request.size = 15;

            var sql = new StringBuilder();
            var countSql = new StringBuilder();

            // 主查询SQL
            sql.Append(@"SELECT
                DeviceId,
                DeviceCode,
                DeviceName,
                IsActive,
                ActiveCode,
                DeviceState,
                DeviceRemark 
            FROM
                devicemodel 
            WHERE
                IsDel = 0");

            // 计数SQL - 包含相同条件
            countSql.Append(@"SELECT COUNT(*) 
                    FROM devicemodel
                    WHERE IsDel = 0");

            // 添加查询条件
            if (!string.IsNullOrEmpty(request.DeviceCode))
            {
                sql.Append(" AND DeviceCode = @DeviceCode");
                countSql.Append(" AND DeviceCode = @DeviceCode");
            }

            if (!string.IsNullOrEmpty(request.DeviceName))
            {
                sql.Append(" AND DeviceName LIKE @DeviceName");
                countSql.Append(" AND DeviceName LIKE @DeviceName");
            }

            // 添加排序和分页
            sql.Append(" ORDER BY DeviceId LIMIT @size OFFSET @offset");

            // 设置参数
            var parameters = new
            {
                DeviceCode = request.DeviceCode,
                DeviceName = string.IsNullOrEmpty(request.DeviceName) ? null : $"%{request.DeviceName}%",
                offset = (request.index - 1) * request.size,
                size = request.size
            };

            try
            {

                // 执行查询
                var pageData = await db.DapperConnection.QueryAsync<DeviceModel>(sql.ToString(), parameters);
                int totalCount = await db.DapperConnection.ExecuteScalarAsync<int>(countSql.ToString(), parameters);
                int totalPage = (int)Math.Ceiling(totalCount / (double)request.size);

                // 设置返回结果
                paging.Msg = "设备查询成功";
                paging.Code = ApiEnum.OK;
                paging.Data = pageData.ToList();
                paging.TotalCount = totalCount;
                paging.TotalPCount = totalPage;
            }
            catch (Exception ex)
            {
                logger.LogError(ex, "设备查询失败 - SQL: {sql}, 参数: {@parameters}", sql.ToString(), parameters);
                paging.Code = ApiEnum.Fail;
                paging.Msg = "设备查询失败";
            }

            return paging;
        }
    }
}
